#include "PadParser.h"

#include "LocationParser.h"
#include "PinRefParser.h"
#include "FeatureParser.h"
#include "XformParser.h"
#include "QStringParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

PadParser::PadParser(
    QStringParser *&_padstackDefRefParser
    , XformParser *&_xformParser
    , LocationParser *&_locationParser
    , FeatureParser *&_featureParser
    , PinRefParser *&_pinRefParser
):    m_padstackDefRefParser(_padstackDefRefParser)
    , m_xformParser(_xformParser)
    , m_locationParser(_locationParser)
    , m_featureParser(_featureParser)
    , m_pinRefParser(_pinRefParser)
{

}

bool PadParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new Pad());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("padstackDefRef")))
    {
        data = reader->attributes().value(QStringLiteral("padstackDefRef"));
        if (!m_padstackDefRefParser->parse(reader, data))
            return false;
        m_result->padstackDefRef = m_padstackDefRefParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("padstackDefRef: Attribute is required"));
        return false;
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
        if (name == QStringLiteral("Xform"))
        {
            if (!m_xformParser->parse(reader))
                return false;
            auto result = m_xformParser->result();
            m_result->xformOptional = Optional<Xform*>(result);
        }
        else if (name == QStringLiteral("Location"))
        {
            if (!m_locationParser->parse(reader))
                return false;
            auto result = m_locationParser->result();
            m_result->location = result;
        }
        else if (m_featureParser->isSubstitution(name))
        {
            if (!m_featureParser->parse(reader))
                return false;
            auto result = m_featureParser->result();
            m_result->feature = result;
        }
        else if (name == QStringLiteral("PinRef"))
        {
            if (!m_pinRefParser->parse(reader))
                return false;
            auto result = m_pinRefParser->result();
            m_result->pinRefOptional = Optional<PinRef*>(result);
        }
        else
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

Pad *PadParser::result()
{
    return m_result.take();
}

}